import React, { useState, useEffect, useRef } from 'react';
import type { FormEvent, ChangeEvent } from 'react';
import { useNavigate } from 'react-router-dom';
import styled, { keyframes } from 'styled-components';
import { motion } from 'framer-motion';
import backIcon from '../assets/images/back-icon.png';

// Define a subtle breathing/pulsing animation for the background (optional replacement for clouds)
const subtlePulse = keyframes`
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
`;

const PageContainer = styled.div`
  min-height: 100vh;
  width: 100vw;
  /* A calmer, more sophisticated gradient */
  background: linear-gradient(160deg, #e0eafc 0%, #cfdef3 100%); 
  overflow: hidden;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 70px; // Adjusted for header

  /* Optional: very subtle animated pattern instead of clouds */
  /* &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 200%; 
    height: 200%;
    background-image: linear-gradient(45deg, rgba(255,255,255,0.03) 25%, transparent 25%, transparent 50%, rgba(255,255,255,0.03) 50%, rgba(255,255,255,0.03) 75%, transparent 75%, transparent);
    background-size: 60px 60px;
    animation: ${subtlePulse} 200s linear infinite;
    transform: translate(-50%, -50%); // Center the animation origin for smoother large-scale movement
    opacity: 0.7;
    z-index: 0;
  } */
`;

const Header = styled.header`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  padding: 12px 20px;
  background-color: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(10px);
  box-shadow: 0 1px 8px rgba(0, 0, 0, 0.08);
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: center;
`;

const BackButton = styled.button`
  background: url(${backIcon}) no-repeat center center;
  background-size: contain;
  width: 24px;
  height: 24px;
  border: none;
  cursor: pointer;
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
  padding: 0;
  opacity: 0.7;
  transition: opacity 0.2s ease;

  &:hover {
    opacity: 1;
  }
`;

const Title = styled.h1`
  font-size: 1.4rem;
  color: #3a506b; // A deeper, calmer blue-grey
  font-weight: 500; // Less bold for a softer look
  margin: 0;
`;

const ChatWrapper = styled(motion.div)`
  width: 90%;
  max-width: 750px; // Slightly reduced max-width
  height: calc(100vh - 70px - 30px - 75px); // header - topMargin - inputArea
  background: rgba(255, 255, 255, 0.35); // Adjusted alpha for glass effect
  backdrop-filter: blur(15px); // Increased blur
  border-radius: 20px; // Softer radius
  box-shadow: 0 6px 25px rgba(0, 0, 0, 0.08);
  z-index: 1;
  display: flex;
  flex-direction: column;
  margin-top: 15px;
  overflow: hidden;
`;

const MessageArea = styled.div`
  flex-grow: 1;
  padding: 25px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px; // Adjusted gap
  &::-webkit-scrollbar {
    width: 5px;
  }
  &::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.15);
    border-radius: 10px;
  }
  &::-webkit-scrollbar-track {
    background-color: transparent;
  }
`;

interface MessageBubbleProps {
  issenderai: "true" | "false";
}

const MessageBubble = styled(motion.div)<MessageBubbleProps>`
  padding: 12px 18px;
  border-radius: 22px; // Softer radius
  max-width: 75%; // Slightly increased max-width
  word-wrap: break-word;
  font-size: 0.9rem;
  line-height: 1.6;
  box-shadow: 0 1px 3px rgba(0,0,0,0.06);

  ${({ issenderai }) =>
    issenderai === 'true'
      ? `
          background-color: #ffffff; // AI: Clean white
          color: #3a506b; // AI: Text color matching title for consistency
          align-self: flex-start;
          border-bottom-left-radius: 6px;
        `
      : `
          /* User: A calm, trustworthy blue gradient */
          background: linear-gradient(135deg, #0061ff 0%, #0049c6 100%); 
          color: white;
          align-self: flex-end;
          border-bottom-right-radius: 6px;
        `}
`;

const InputArea = styled.form`
  padding: 15px 20px; // Adjusted padding
  border-top: 1px solid rgba(0, 0, 0, 0.07);
  background-color: rgba(255,255,255,0.2);
  backdrop-filter: blur(10px); 
  display: flex;
  align-items: center;
  gap: 12px;
  min-height: 75px;
`;

const TextInput = styled.input`
  flex-grow: 1;
  padding: 12px 18px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 22px; // Match bubble radius
  background-color: rgba(255, 255, 255, 0.7);
  font-size: 0.9rem;
  color: #222;
  outline: none;
  transition: border-color 0.2s ease, background-color 0.2s ease;

  &:focus {
    border-color: #0061ff;
    background-color: rgba(255, 255, 255, 0.9);
  }

  &::placeholder {
    color: #777;
  }
`;

const SendButton = styled.button`
  padding: 10px 18px;
  border: none;
  border-radius: 22px; // Match bubble radius
  /* Send Button: Using a consistent action color, matching user bubble */
  background: linear-gradient(135deg, #0061ff 0%, #0049c6 100%); 
  color: white;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: transform 0.15s ease, box-shadow 0.15s ease, opacity 0.15s ease;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover:not(:disabled) {
    transform: scale(1.03);
    box-shadow: 0 3px 10px rgba(0, 73, 198, 0.25);
  }
  
  &:active:not(:disabled) {
    transform: scale(0.98);
  }

  &:disabled {
    background: #b0bec5; // A clearer disabled state
    opacity: 0.7;
    cursor: not-allowed;
  }
`;

// Typing indicator (simple pulsing dots or a blinking cursor)
const TypingIndicator = styled(motion.span)`
  display: inline-block;
  margin-left: 5px;
  span {
    display: inline-block;
    width: 4px;
    height: 4px;
    background-color: currentColor;
    border-radius: 50%;
    margin: 0 1px;
    animation: ${keyframes`0%, 100% { opacity: 0.3; transform: scale(0.7); } 50% { opacity: 1; transform: scale(1); }`} 1.2s infinite ease-in-out;
  }
  span:nth-of-type(1) { animation-delay: 0s; }
  span:nth-of-type(2) { animation-delay: 0.2s; }
  span:nth-of-type(3) { animation-delay: 0.4s; }
`;

const AITalkPage: React.FC = () => {
  const [messages, setMessages] = useState<{ id: string; text: string; sender: 'user' | 'ai'; isTyping?: boolean }[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [isLoading, setIsLoading] = useState(false); // For AI response loading
  const messagesEndRef = useRef<null | HTMLDivElement>(null);
  const messageAreaRef = useRef<null | HTMLDivElement>(null); // Ref for MessageArea
  const navigate = useNavigate(); // Initialize navigate

  const welcomeMessageText = "欢迎来到心灵港湾，这里有温柔的聆听和真诚的陪伴，愿每一句话都为你带来宁静与力量。";

  const handleBack = () => {
    navigate(-1); // Go back to the previous page
  };

  useEffect(() => {
    // Initial welcome message with typing effect
    const welcomeId = `ai-welcome-${Date.now()}`;
    setMessages([{ id: welcomeId, text: '', sender: 'ai', isTyping: true }]);
    let currentText = '';
    let charIndex = 0;
    const typingInterval = setInterval(() => {
      if (charIndex < welcomeMessageText.length) {
        currentText += welcomeMessageText[charIndex];
        setMessages(prev => prev.map(m => m.id === welcomeId ? { ...m, text: currentText } : m));
        charIndex++;
      } else {
        clearInterval(typingInterval);
        setMessages(prev => prev.map(m => m.id === welcomeId ? { ...m, isTyping: false } : m));
      }
    }, 35); // Adjusted typing speed

    return () => clearInterval(typingInterval);
  }, []);

  useEffect(() => {
    // Scroll logic
    const isOnlyWelcomeMessage = messages.length === 1 && messages[0].id.startsWith('ai-welcome-');

    if (isOnlyWelcomeMessage) {
      if (messageAreaRef.current) {
        // For the welcome message (typing or finished), keep scroll at top
        // as long as it's the only message.
        messageAreaRef.current.scrollTop = 0;
      }
    } else {
      // For subsequent messages, or if other messages appear, scroll to bottom.
      if (messagesEndRef.current) {
        messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
      }
    }
  }, [messages, messages[messages.length - 1]?.text, messages[messages.length - 1]?.isTyping]); // Enhanced dependencies

  const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (!inputValue.trim() || isLoading) return;

    const userMessageText = inputValue.trim();
    const userMessage = {
      id: `user-${Date.now()}`,
      text: userMessageText,
      sender: 'user' as const,
    };
    setMessages(prev => [...prev, userMessage]);
    setInputValue('');
    setIsLoading(true);

    const aiResponseId = `ai-response-${Date.now()}`;
    setMessages(prev => [...prev, { id: aiResponseId, text: '', sender: 'ai', isTyping: true }]);

    try {
      const response = await fetch(`http://localhost:8111/api/talk?prompt=${encodeURIComponent(userMessageText)}`, {
        method: 'POST',
      });

      if (!response.ok) {
        let errorDetail = `API请求失败，状态码: ${response.status}`;
        try {
          // 尝试解析JSON格式的错误信息
          const errorData = await response.json();
          errorDetail = errorData.message || errorData.error || errorDetail; //  常见的错误信息字段
        } catch (e) {
          // 如果JSON解析失败，尝试读取纯文本错误信息
          const errorText = await response.text().catch(() => null); //  读取文本，如果失败则为null
          if (errorText && errorText.length < 200) { // 避免过长的非错误文本被当作错误详情
            errorDetail = errorText; 
          }
        }
        throw new Error(errorDetail);
      }

      // API成功返回，但内容是纯文本
      const aiText = await response.text(); 

      if (!aiText || aiText.trim() === '') {
          // 如果AI返回空字符串，也视为一种需要提示的情况
          setMessages(prev => prev.map(m => m.id === aiResponseId ? { ...m, text: "AI似乎没有返回具体内容。", isTyping: false } : m));
          setIsLoading(false);
          return; // 提前退出，不再进行打字动画
      }
      
      // AI 回复打字效果
      let currentAiText = '';
      let aiCharIndex = 0;
      const aiTypingInterval = setInterval(() => {
        if (aiCharIndex < aiText.length) {
          currentAiText += aiText[aiCharIndex];
          setMessages(prev => prev.map(m => m.id === aiResponseId ? { ...m, text: currentAiText } : m));
          aiCharIndex++;
        } else {
          clearInterval(aiTypingInterval);
          setMessages(prev => prev.map(m => m.id === aiResponseId ? { ...m, isTyping: false } : m));
          setIsLoading(false);
        }
      }, 35); // AI打字速度，与欢迎语一致

    } catch (error) {
      console.error("Error fetching AI response:", error);
      let errorMessage = "与服务器连接时发生错误，请稍后再试。";
      if (error instanceof Error) {
        errorMessage = error.message;
      }
      setMessages(prev => prev.map(m => m.id === aiResponseId ? { ...m, text: `错误: ${errorMessage}`, isTyping: false, sender: 'ai' } : m));
      setIsLoading(false);
    }
  };

  return (
    <PageContainer>
      <Header>
        <BackButton onClick={handleBack} aria-label="Go back" />
        <Title>心灵港湾 · AI心理咨询助手</Title>
      </Header>
      <ChatWrapper
        initial={{ opacity: 0, y: 30 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.6, ease: [0.25, 0.46, 0.45, 0.94] }}
      >
        <MessageArea ref={messageAreaRef}>
          {messages.map((msg) => (
            <MessageBubble
              key={msg.id}
              issenderai={(msg.sender === 'ai').toString() as "true" | "false"}
              initial={{ opacity: 0, scale: 0.8, y: 15 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              transition={{ duration: 0.3, ease: "easeOut" }}
            >
              {msg.text}
              {msg.isTyping && (
                <TypingIndicator initial={{opacity:0}} animate={{opacity:1}} transition={{delay:0.2}}>
                  <span></span><span></span><span></span>
                </TypingIndicator>
              )}
            </MessageBubble>
          ))}
          <div ref={messagesEndRef} />
        </MessageArea>
        <InputArea onSubmit={handleSubmit}>
          <TextInput
            type="text"
            placeholder="聊聊你的心事吧..."
            value={inputValue}
            onChange={(e: ChangeEvent<HTMLInputElement>) => setInputValue(e.target.value)}
            disabled={isLoading}
            onKeyPress={(e) => {
              if (e.key === 'Enter' && !e.shiftKey && inputValue.trim() && !isLoading) {
                handleSubmit(e as any); // Cast to any for form event, or wrap in a form submit call
              }
            }}
          />
          <SendButton type="submit" disabled={isLoading || !inputValue.trim()}>
            发送
          </SendButton>
        </InputArea>
      </ChatWrapper>
    </PageContainer>
  );
};

export default AITalkPage;
